#include "tiantianspider.h"

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

static const QString tiantianUrlHead = "http://fundgz.1234567.com.cn/js/";
static const QString tiantianUrlTail = ".js";

TiantianSpider::TiantianSpider(QObject *parent) : QObject(parent) {
    clear();
    accessManger = new QNetworkAccessManager(this);
    QObject::connect(accessManger, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
}

TiantianSpider::~TiantianSpider() {
    accessManger->deleteLater();
}

void TiantianSpider::clear() {
    resultList.clear();
}

void TiantianSpider::ask(QString code) {
//    qDebug() << QSslSocket::supportsSsl();
//    qDebug() << QSslSocket::sslLibraryBuildVersionString();
    // Clear data first
    clear();
    resultList.append(code);
    // Net request part
    QNetworkRequest request;
//    QNetworkAccessManager* accessManger = new QNetworkAccessManager(this);
    QString url = tiantianUrlHead + code + tiantianUrlTail;
    request.setUrl(QUrl(url));
    accessManger->get(request);
}

void TiantianSpider::requestFinished(QNetworkReply *reply) {
    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(!statusCode.isValid()) {
        emit finished(false);
        return;
    }

    QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    if(!reason.isValid()) {
        qDebug() << "status code=" << statusCode.toInt();
        emit finished(false);
        return;
    }

    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError) {
        qDebug() << "Failed: " << reply->errorString();
        qDebug() << "reason=" << reason.toString();
        emit finished(false);
    } else {
        QByteArray bytes = reply->readAll();
        QString string = QString::fromUtf8(bytes).simplified();
        analyze(string);
    }
    reply->deleteLater();
}

void TiantianSpider::analyze(QString str) {
    QRegExp exp("[{](.*)[}]");
//    Do not delete below
//    qDebug() << "index:" << exp.indexIn(str);
//    if(str.indexOf(exp) >= 0) {
//        qDebug() << "something cap:" << exp.matchedLength();
//        qDebug() << exp.cap(0);
//    } else {
//        emit finished(false);
//        return;
//    }
    if(str.indexOf(exp) < 0) {
        emit finished(false);
        return;
    }

    QString name = "null";
    QJsonParseError jsonError;
    QByteArray jsonArray = exp.cap(0).toUtf8();
    QJsonDocument  jsonDoucment = QJsonDocument::fromJson(jsonArray, &jsonError);
    if(jsonError.error != QJsonParseError::NoError) {
        qDebug() << "FundDB get json data failed: " << jsonError.error;
        emit finished(false);
        return;
    }

    QJsonObject jsonRootObj = jsonDoucment.object();

    QString code = jsonRootObj.value("fundcode").toString();
    name = jsonRootObj.value("name").toString();
    QString net_valua_date = jsonRootObj.value("jzrq").toString();
    QString unit_net_value = jsonRootObj.value("dwjz").toString();
    QString estimated_value = jsonRootObj.value("gsz").toString();
    QString estimated_percent = jsonRootObj.value("gszzl").toString();
    QString estimated_date = jsonRootObj.value("gztime").toString();
    QString estimated_timestamp = QString::number(QDateTime::fromString(estimated_date, "yyyy-MM-dd hh:mm").toTime_t());

    resultList.clear();
    resultList.append(code);
    resultList.append(name);
    resultList.append(net_valua_date);
    resultList.append(unit_net_value);
    resultList.append(estimated_value);
    resultList.append(estimated_percent);
    resultList.append(estimated_date);
    resultList.append(estimated_timestamp);

    emit finished(true);
}

QList<QString> TiantianSpider::getList() {
    return resultList;
}
